package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.OrdersMapper;
import com.zhentao.pojo.Orders;
import com.zhentao.service.OrdersService;
import com.zhentao.vo.QueryParam;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author ls
* @description 针对表【orders】的数据库操作Service实现
* @createDate 2025-07-01 15:29:55
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService{
    @Autowired
    private OrdersMapper ordersMapper;
    @Override
    public Page<Orders> findOrders(QueryParam queryParam) {
        Page<Orders> page = new Page<>(queryParam.getCurrent(), queryParam.getSize());
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();

        // 只有当orderSn非空时才添加条件
        if (StringUtils.isNotBlank(queryParam.getOrderSn())) {
            queryWrapper.like("order_sn", queryParam.getOrderSn());
        }

        // 添加默认排序
        queryWrapper.orderByDesc("create_time");

        return ordersMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Result getOrderStats() {
        // 订单总数
        long totalCount = this.count();
        // 订单总金额
        Double totalAmount = this.lambdaQuery().select(Orders::getTotalAmount).list()
            .stream().mapToDouble(o -> o.getTotalAmount() == null ? 0 : o.getTotalAmount()).sum();
        // 订单状态分布
        Map<Integer, Long> statusMap = this.lambdaQuery().list().stream()
            .collect(Collectors.groupingBy(Orders::getStatus, Collectors.counting()));
        // 近7天订单数量趋势
        List<Map<String, Object>> trend = new ArrayList<>();
        LocalDate today = LocalDate.now();
        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            long count = this.lambdaQuery()
                .between(Orders::getCreateTime, java.sql.Timestamp.valueOf(date.atStartOfDay()), java.sql.Timestamp.valueOf(date.plusDays(1).atStartOfDay()))
                .count();
            Map<String, Object> day = new HashMap<>();
            day.put("date", date.toString());
            day.put("count", count);
            trend.add(day);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", totalCount);
        result.put("totalAmount", totalAmount);
        result.put("statusMap", statusMap);
        result.put("trend", trend);
        return Result.OK(result);
    }

    @Override
    public boolean updateOrderStatus(String orderSn, String status, String totalAmount) {
        Orders order = this.lambdaQuery().eq(Orders::getOrderSn, orderSn).one();
        if (order == null) {
            return false;
        }
        // 假设 status "PAID" 对应数据库的已支付状态码 2
        order.setStatus(2);
        if (totalAmount != null) {
            try {
                order.setTotalAmount(Double.valueOf(totalAmount));
            } catch (Exception ignored) {}
        }
        order.setUpdateTime(new java.util.Date());
        return this.updateById(order);
    }
}




